package com.vchecker.iobd_checker.utils;


import android.content.Context;
import android.os.Environment;

import com.vchecker.iobd_checker.model.CommDefine;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Yipb on 16-4-18.
 */
public class Upgrad {
    private static final String TAG = "Upgrad";
    public static String UPGRAD_PATH_SDCARD_DIR = Environment
            .getExternalStorageDirectory().getAbsolutePath()
            + File.separator
            + "vchecker_pkg" + File.separator;


    public class VerInfo {
        public String name;
        public String lanId;    //设备语言代码 0:中文简体 1:中文繁体 2:英文
        public float maxMcuVer;
        public float maxBinVer;
        public String maxMcuVerFile;
        public String maxBinVerFile;

        VerInfo() {
            name = "";
            lanId = "";
            maxMcuVer = 0;
            maxBinVer = 0;
            maxMcuVerFile = "";
            maxBinVerFile = "";
        }
    }

    Map<String, VerInfo> mapVerInfo = new HashMap<String, VerInfo>();

    File fileMcu = null;
    File fileFlash = null;

    Context mContext = null;
    // 单例
    private static Upgrad mInstance = null;

    public static synchronized Upgrad getInstance() {
        if (mInstance == null)
            mInstance = new Upgrad(null);
        return mInstance;
    }

    public Upgrad(Context context) {
        mContext = context;
        mInstance = this;
    }

    public boolean updateUpgradFile() {
        boolean bRet = false;
        try {
            String[] pkgNew = mContext.getResources().getAssets().list("pkg");
            // 检测/创建升级的文件夹
            File dir = new File(UPGRAD_PATH_SDCARD_DIR);
            if (!dir.exists()) {
                dir.mkdirs(); // 创建多级目录
                dir = new File(UPGRAD_PATH_SDCARD_DIR);
            }

            //清空升级包目录
            String fullName = "";
            String extName = "";
            for (File f : dir.listFiles()) {
                fullName = f.getName();
                f.delete();
            }

            // 从资源中读取升级库流
            for (String s : pkgNew) {
                InputStream input = null;
                OutputStream output = null;
                try {
                    input = mContext.getResources().getAssets().open("pkg/" + s);
                    output = new FileOutputStream(UPGRAD_PATH_SDCARD_DIR + s);

                    // 拷贝到输出流
                    byte[] buffer = new byte[2048];
                    int length;
                    while ((length = input.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    bRet = true;


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭输出流
                    try {
                        output.flush();
                        output.close();
                    } catch (IOException e) {
                    }
                    // 关闭输入流
                    try {
                        input.close();
                    } catch (IOException e) {
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
            CommDefine.addLog(TAG,"初始化升级库失败:" + e.toString());
            return false;
        }

        initMaxVer();

//        for (Map.Entry<String,VerInfo> entry : mapVerInfo.entrySet()){
//            Log.i(TAG,entry.getKey());
//            Log.i(TAG,entry.getValue().maxMcuVer + " = " + entry.getValue().maxMcuVerFile);
//            Log.i(TAG,entry.getValue().maxBinVer + " = " + entry.getValue().maxBinVerFile);
//        }
        return bRet;
    }

    public void initMaxVer() {
        // 检测/创建升级的文件夹
        File dir = new File(UPGRAD_PATH_SDCARD_DIR);
        String name = "";
        String lan = "";
        String lanId = "";
        String fullName = "";
        String extName = "";
        String fileVersion = "0";

        VerInfo vi = null;
        for (File f : dir.listFiles()) {
            fullName = f.getName();
            extName = fullName.substring(fullName.length() - 3, fullName.length());
            name = fullName.substring(0, 4);
            if (fullName.indexOf("_en") > 0) {
                lan = "_en";
                lanId = "2";
            } else if (fullName.indexOf("_ru") > 0) {
                lan = "_ru";
                lanId = "7";
            } else if (fullName.indexOf("_zh_CN") > 0) {
                lan = "_zh_CN";
                lanId = "0";
            } else {
                continue;
            }
            vi = mapVerInfo.get(name + lan);
            if (vi == null) {
                vi = new VerInfo();
                vi.name = name;
                vi.lanId = lanId;
                mapVerInfo.put(name + lan, vi);
            }
            if (extName.equals("PKG")) {
                fileVersion = fullName.replace(name + "_MCU_V", "");
                fileVersion = fileVersion.replace(lan + ".PKG", "");
                if (Float.valueOf(fileVersion) > vi.maxMcuVer) {
                    vi.maxMcuVer = Float.valueOf(fileVersion);
                    vi.maxMcuVerFile = f.getPath();
                }
            }

            if (extName.equals("BIN")) {
                fileVersion = fullName.replace(name + "_Flash_V", "");
                fileVersion = fileVersion.replace(lan + ".BIN", "");
                if (Float.valueOf(fileVersion) > vi.maxBinVer) {
                    vi.maxBinVer = Float.valueOf(fileVersion);
                    vi.maxBinVerFile = f.getPath();
                }
            }
        }
    }

    public VerInfo getMaxVerInfo(String name) {
        if (mapVerInfo.containsKey(name)) {
            return mapVerInfo.get(name);
        } else {
            return null;
        }
    }

    public static byte[] getByteArrayFromFile(String fileName) {
        File file = null;
        try {
            file = new File(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        if (!file.exists() || !file.isFile() || !file.canRead()) {
            return null;
        }

        byte[] byteArray = null;

        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int count;
            byte buffer[] = new byte[1024];
            while ((count = fis.read(buffer)) > 0) {
                baos.write(buffer, 0, count);
            }
            byteArray = baos.toByteArray();
            fis.close();
            baos.flush();
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return byteArray;
    }
}
